/*
 * Javascript Validation 
 * Created by         : Kien Vo
 * Last Modified      : Jun 29, 2008 
 */

jQuery.extend({
	
	fValidator: function(formName){
		this.frmObj = document.forms[frmName];
		if(!this.frmObj){
			alert("ERROR: Could not get form object(s) " + frmName);
			return;
		}
		
		if(this.frmObj.onSubmit){
			this.frmObj.oldOnSubmit = this.frmObj.onSubmit;
			this.frmObj.onSubmit = null;
		}
		else this.frmObj.oldOnSubmit = null;
		
		this.frmObj.formName = frmName;
		this.frmObj.onSubmit = fSubmitHandler;
		this.addValidation = fAddValidation;
		this.setAddnlValidationFunction = fSetAddNlvFuntion;
		this.clearAllValidations = fClearAllValidation;
		this.disableValidations = false
		document.errorDispHandler = new fErrorDisplayHandler();
		this.enableOnPageErrorDisplay = fValidatorEnableOPED;
		this.enableOnPageErrorDisplaySingleBox = fValidatorEnableOPEDSB;
		this.showErrorsTogether = true;
		this.enableMsgsTogether = fEnableShowMsgTogether;	
	}
	
	fSetAddNlvFunction: function(funcName){
		this.frmObj.addNlvalidation = funcName;
	}
	
	fEnableShowMsgTogether: function(){
		this.showErrorsTogether = true;
		this.frmObj.showErrorsTogether = true;
	}
	
	fClearAllValidation: function(){
		for(key in this.frmObj.elements)
			this.frmObj.elements[key].validationSet = null;
	}
	
	fFormSubmitHandler: function(){
		var bRet = true;
		document.errorDispHandler.fClearMsgs();
		for(key in this.elements){
			if(this.elements[key].validationSet && !this.elements[key].validationSet.validate())
				bRet = false;
			
			if(!bRet && !this.showErrorsTogether) break;
		}
		
		if(!bRet){
			document.erroDispHandler.fFinalShowMsg();
			return false;
		}
		
		if(this.addNlvalidation){
			str =" var ret = " + this.addNlvalidation + "() ";
			eval(str);
			if(!ret) return ret;
		}
		return true;
	}
	
	fAddValidation: function(){
		var condition = null;
		if(arguments.length > 3) { condition = argument[3]; }
		
		if(!this.frmObj){
			alert("ERROR: The form object is not set property");
			return;
		}
		var itemObj = this.frmObj[itemName];
		
		// Used for radio button
		if(itemObj.legnth && isNaN(itemObj.selectedIndex)){
			itemObj = itemObj[0];
		}
		
		if(!itemObj){
			alert("ERROR: Could not get the input object name: " + itemName);
			return;
		}
		if(!itemObj.validationSet){ itemObj.validationSet = new ValidationSet(itemObj, this.showErrorsTogether) };
		
		itemObj.validationSet.add(descriptor, errStr, condition);
		itemObj.validatorObj = this;
	}
	
	fValidatorEnableOPED: function(){
		document.errorDispHandler.EnableOnPageDisplay(false);
	}
	
	fValidatorEnableOPEDSB: function(){
		document.errorDispHandler.EnableOnPageDisplay(true);
	}
	
	fErrorDispHandler: function(){
		this.msgDisplay = new AlertMsgDisplay();
		this.enableOnPageDisplay = edhEnableOnPageDisplay;
		this.showMsg = edhFinalShowMsg;
		this.allMsgs = new Array();
		this.clearMsgs = edhClearMsgs;
	}
	
	fEdhClearMsgs: function(){
		this.msgDisplay.clearmsg(this.allMsgs);
		this.allMsgs = new Array();
	}
	
	fEdhFinalShowMsg: function(){
		this.msgDisplay.fShowMsg(this.allMsgs);
	}
	
	fEdhEnableOnPageDisplay(singleBox){
		if(true == singleBox){ this.msgDisplay = new SingleBoxErrorDisplay(); }
		else { this.msgDisplay = new DivMsgDisplayer(); }
	}
	
	fEdhShowMsg: function(msg, inElement){
		var objMsg = new Array();
		objMsg["input_element"] = inElement;
		objMsg["msg"] = msg;
		this.allMsgs.push(objMsg);
	}
	
	fAlertMsgDisplayer: function(){
		this.showMsg = fAlertShowMsg;
		this.clearMsg = fAlertClearmsg;
	}
	
	fAlertShowMsg: function(msgs){
		var wholeMsg = "";
		var firstElement = null;
		
		for(var m in msgs){
			if(null == firstElement)
				firstElement = msgs[m]["input_element"];
			
			wholeMsg += msgs[m]["msg"] + ""\n;
		}
		
		alert(wholeMsg);
		if(null!=firstElement) { firstElement.focus(); }
	}
			
	fAlertClearMsg: function(msgs){}
	
	fShowErrorMsg: function(msg,input_elmt){
	    document.errorDispHandler.ShowMsg(msg,input_elmt);
	}	
	
	fSingleBoxErrorDisplay: function(){
		this.showMsg = fDivShowMsg;
		this.clearMsg = fDivClearMsg;
	}
	
	fDivClearMsg: function(msgs){
		var divName = fErrorDivName(msgs);
		fShowDivMsg(divName, "");
	}
	
	fDivShowMsg: function(msgs){
		var wholeMsg = "<ul>\n";
		for(var m in msgs)
			wholeMsg += "<li>" + msgs[m]["msg"] + "</li>\n";
		
		wholeMsg += "</u>";
		var divName = fFormErrorDivName(msgs);
		fShowDivMsg(divName,wholeMsg);
	}
	
	fFormErrorDivName: function(msgs){
		var inputElement = null;
		
		for(var m in msgs){
			inputElement = msgs[m]["input_element"];
			if(inputElement) { break; }
		}
		
		var divName = "";
		if(inputElement){ divName = inputElement.form.formName + "_errorloc"; }
		return divName;
	}
	
	fDivMsgDisplayer: function(){
		this.showMsg = divShowMsg();
		this.clearMsg = divClearMsg();
	}
	
	fDivClearMsg: function(msgs){
		for(var m in msgs){
			var divName = fElementDivName(msgs[m]["input_element"]);
			fShowDivMsg(divName,"");
		}
	}
	
	fElementDivName: function(inElement){
		var divName = inElement.form.fFormName.formName + "_" + inElement.name + "_errorloc";
		divName = divName.replace(/[\[\]]/gi, "")
		return divName;
	}
	
	fDivShowMsg: function(msgs){
		var wholeMsg;
		var firstElement = null;
		for(var m in msgs){
			if(null == firstElement)
				firstElement = msgs[m]["input_element"];
				
			var divName = fElementDivname(msgs[m]["input_element"]);
			fShowDivMsg(divName, msgs[m]["msg"]);
		}
		if(null!=firstElement){ firstElement.focus(); }
	} 
	
	fShowDivMsg: function(divName, msgsStr){
		if(divName.length <= 0 ) return false;
		
		if(document.layers){
			divLayer = document.layers[divName];
			if(!divLayer){ return; }
			divLayer.document.open();
			divLayer.document.write(msgsStr);
			divLayer.document.close();
		}
		else if(document.all){
			divLayer = document.all[divName];
			if(!divLayer){ return; }
			divLayer.innerHTML = msgStr;
		}
		else if(document.getElementById){
			divLayer = document.getElementById(divName);
			if(!divLayer){ return; }
			divLayer.innerHTML = msgsStr;
		}
		divLayer.style.visibility = "visible";
		return false;
	}
	
	fValidationDesc: function(inputItem, desc, error, condition){
		this.desc = desc;
		this.error = error;
		this.itemObj = inputItem;
		this.condition = condition;
		this.validate = fVDescValidate;
	}
	
	fVDescValidate: function(){
		if(this.condition != null){ 
			if(!eval(this.condition)){ return true; }
		}
		
		if(!fValidateInput(this.desc, this.itemObj, this.error)){
			this.itemObj.validatorObj.disableValidations = true;
			this.itemObj.focus();
			return false;
		}
		return true;
	}
	
	fValidationSet(inputItem, msgsTogether){
		this.vSet = new Array();
		this.add = fAddValidationDesc;
		this.validate = fVSetValidate;
		this.itemObj = inputItem;
		this.msgsTogether = msgsTogether;
	}
	
	fAddValidationDesc: function(desc, error, condition){
		this.vSet[this.vSet.length] = new fValidationDesc(this.itemObj, desc, error, condition);
	}
	
	fVSetValidate: function(){
		var bRet = true;
		for(key in this.vSet){
			bRet = bRet && this.vSet[key].validate();
			if(!bRet && !this.msgsTogether) { break; }
		}
		return bRet;
	}
	
	fValidateEmail: function(email){
		var splitted = email.match("^(.+)@(.+)$");
		
		if(splitted == null) return false;
		if(splitted[1] != null){
			var regexp_account =/^\"?[\w-_\.]*\"?$/;
			if(splitted[1].match(regexp_account) == null) return false;
		}
		if(splitted[2] != null){
			var regexp_domain =/^[\w-\.]*\.[A-Za-z]{2,4}$/;
			if(splitted[2].match(regexp_domain) == null){
				var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
				if(splitted[2].match(regexp_ip) == null) return false; 
			}
			return true;
		}
		return false;
	}
	
	fIsCheckSelected: function(objValue, chkValue){
		var seleted = false;
		var objCheck = objValue.form.elements[objValue.name];
		if(objCheck.length){
			var idxChk = -1;
			var count = 0;
			
			for(key in objCheck){
				if(objCheck[key].value == chkValue){
					idxChk = count;
					break; 
				}
				count++;
			}
			
			if(idxChk >= 0){
				if(objCheck[idxChk].checked == "1"){ selected = true; }
			}
		}
		else{
			if(objValue.checked == "1"){
				selected = true;
			}
		}
		return selected;		
	}
	
	fChkNonSelected: function(objValue, chkValue, strError){
		var pass = true;
		pass = fIsCheckSelected(objValue, chkValue) ? false : true;
		
		if(pass == false){
			if(!strError || strError.length==0)
			{
				strError = "Cannot proceed as you selected " + objValue.name;
			}
			fShowErrorMsg(strError, objValue);			
		}
		return pass;
	}
	
	fSelectRequired: function(objVal, chkVal, strError){
		var pass = true;
		pass = fIsCheckSelected(objVal, chkVal) ? true : false;
		
		if(pass == false){
			if(!strError || strErro.length == 0){
				strError = "You should select " + objVal.name;
			}
			fShowErrorMsg(strError, objVal);
		}
		return pass;
	}
	
	fInputRequired: function(objVal, strError){
		var ret = true;
		if(eval(objVal.value.length) == 0){
			if(!strError || strError.length == 0){ 
				strError = objVal.name + " : Required field!"; 
			}
			fShowErrorMsg(strError, objVal);
			ret = false;
		}
		return ret;
	}
	
	fCheckMaxLen: function(objVal, strMaxLen, strError){
		var ret = true;
		if(eval(objVal.value.length) > eval(strMaxLen)){
			if(!strError || strError.length == 0){
				strError = objVal.name + " : " + strMaxLen + " characters maximum ";
			}
			fShowErrorMsg(strError, objVal);
			ret = false;
		}
		return ret;
	}
	
	fCheckMinLen: function(objVal, strMinLen, strError){
		var ret = true;
		if(eval(objVal.value.length) < eval(strMinLen)){
			if(!strError || strError.length == 0){
				strError = objVal.name + " : " + strMinLen + " characters minimum ";
			}
			fShowErrorMsg(strError, objVal);
			ret = false;
		}
		return ret;
	}
	
	fCheckInputType: function(objVal, strRegExp, strError, strDefaultError){
		var ret = true;
		var charPos = objVal.value.search(strRegExp);
		if(objVal.value.length > 0 && charPos >= 0){
			if(!strError || strError.length == 0){
				strError = strDefaultError;
			}
			fShowErrorMsg(strError, objVal);
			ret = false;
		} 
		return ret;
	}
	
	fCheckEmail: function(objVal, strError){
		var ret = true;
		if(objVal.value.length > 0 && !fValidateEmail(objVal.value)){
			if(!strError || strError.length = 0){
				strError = objVal.name + ": Enter a valid email address "; 
			}
			fShowErrorMsg(strError, objVal);
			ret false;
		}
		return ret;
	}
	
	fIsNumeric: function(objVal, strError){
		var ret = true;
		if(objVal.value)){
			if(!strError || strError.length == 0){
				fShowErrorMsg(objVal.name + ": Should be a number ", objVal);
			}
			ret = false;
		}
		return ret;
	}
	
	fCheckLessThan: function(objVal, strLessThan, strError){
		var ret = true;
		if(fIsNumeric(objVal.value, "")){
			ret = false;
		}
		else{
			if(eval(objVal.value) > = eval(strLessThan)){
				if(!strError || strError.length == 0){
					strError = objVal.name + " : value should be less than " + strLessThan;
				}
				fShowErrorMsg(strError, objVal);
				ret = false;
			}
		}
		return ret;
	}
	
	fCheckGreaterThan: function(objVal, strGreaterThan, strError){
		var ret = true;
		if(fIsNumeric(objVal.value, "")){
			ret = false;
		}
		else{
			if(eval(objVal.value) <= eval(strGreaterThan)){
				if(!strError || strError.length == 0){
					strError = objVal.name + " : value should be greater than " + strGreaterThan;
				}
				fShowErrorMsg(strError, objVal);
				ret = false;
			}
		}
		return ret;
	}
	
	fCheckRegExp: function(objVal, strRegExp, strError){
		var ret = true;
		if(objVal.value.length > 0 && !objValue.value.match(strRegExp)){
			if(!strError || strError.length == 0){
				strError = objVal.name + ": Invalid characters found ";
			}
			fShowErrorMsg(strError, objVal);
			ret = false;
		}
		return ret;
	}
	
	fCheckInput: function(strValidateStr, objVal, strError){
		var ret = true;
		var ePos = strValidateStr.search("=");
		var command = "";
		var cmdValue = "";
		if(ePos >= 0){
			command = strValidateStr.substring(0, ePos);
			cmdValue = strValidateStr.substr(ePos + 1);
		}
		else { command = strValidateStr; }
		
		switch(command){
			case "req":
			case "required":{
				ret = fCheckRequiredInput(objVal, strError);
				break;	
			}
			case "maxlength":
			case "maxlen":{
				ret = fCheckMaxLen(objVal, cmdValue, strError);
				break;
			}
			case "minlength":
			case "minlen":{
				ret = fCheckMinLen(objVal, cmdValue, strError);
				break;
			}
			case "alnum":
			case "alphanumeric":{
				ret = fCheckInputType(objVal, "[^A-Za-z0-9]", strError,
				                      objVal.name + ": Only alpha-numeric characters allowed " );
				break;
			}
			case "alnum_s":
			case "alphanumeric_space":{
				ret = fCheckInputType(objVal, "[^A-Za-z0-9\\s]", strError,
				                      objVal.name + ": Only alpha-numeric characters and spaces allowed " );
				break;
			}
			case "num":
			case "numeric":{
				ret = fCheckInputType(objVal, "[^0-9]", strError,
				                      objVal.name + ": Only digits allowed " );
				break;
			}
			case "alphabetic":
			case "alpha":{
				ret = fCheckInputType(objVal, "[^A-Za-z]", strError,
				                      objVal.name + ": Only alphabetic characters allowed " );
				break;
			}
			case "alphabetic_space":
			case "alpha_s":{
				ret = fCheckInputType(objVal, "[^A-Za-z\\s]", strError,
				                      objVal.name + ": Only alphabetic characters and spaces allowed " );
				break;
			}
			case "email":{
				ret = fCheckEmail(objVal, strError);
				break;
			}
			case "lt":
			case "lessthan":{
				ret = fCheckLessThan(objVal, cmdValue, strError);
				break;
			}
			case "gt":
			case "greaterthan":{
				ret = fCheckGreaterThan(objVal, cmdValue, strError);
				break;
			}
			case "regexp":{
				ret = fCheckLessThan(objVal, cmdValue, strError);
				break;
			}
			
			
			
		
		}
	}
	
	
	
	



})